package com.haixinga.commbiz.commons.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.SQLOutput;
import java.util.Base64;
import java.util.UUID;

/**
 * @description: StringKit
 * @Author terrfly
 * @Date 2020/02/18 17:28
 */
public class StringKit {

	public static final String CHINESE_REG = "[\\u4e00-\\u9fa5]+"; //判断是否是中文

	public static boolean isEmpty(String str){
		return str == null || str.length() == 0;
	}

	public static boolean isNotEmpty(String str){
		return !isEmpty(str);
	}

	/** 默认值 **/
	public static String defaultVal(String str, String defaultStr){
		return isEmpty(str) ? defaultStr : str;
	}

	public static String getUUID(){
		return UUID.randomUUID().toString().replace("-", "") + Thread.currentThread().getId();
	}

	public static String getUUID(int endAt){
		return getUUID().substring(0, endAt);
	}

	/**
	 * base64 加密
	 * @param text
	 * @return
	 */
	public static String base64Encode(String text){
		if(text == null)
			return null;
		return Base64.getEncoder().encodeToString(text.getBytes());
	}

	/**
	 * base64 解密
	 * @param text
	 * @return
	 */
	public static String base64Decode(String text){
		if(text == null)
			return null;
		return new String(Base64.getDecoder().decode(text.getBytes()));
	}


	/**
	 * URLEncode 仅转码中文，其他字符不变。
	 * @param text
	 * @return
	 */
	public static String urlEncodeOnlyChinese(String text){

		try {
			String result = "";
			for(int i = 0; i < text.length(); i++){
				char c = text.charAt(i);
				 if(isHasChinese(c + "")){
					 result += URLEncoder.encode(c + "", "UTF-8");
				 }else{
					 result += c ;
				 }
			}
			return result;
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}

	/**
	 * 是否包含中文
	 * @param text
	 * @return
	 */
	public static boolean isHasChinese(String text){
		return text.matches(CHINESE_REG);

	}


}
